﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Management;
using System.Net;

namespace Coomtools.commclass
{

    #region 注意事项及使用方法
    /***************************************************************************

    注意事项：
1.using System.Management在使用之前需要添加引用System.Management组件，是个标准.Net组件，文件是system.management.dll
2.新建类库项目，将代码放入，生成解决方案，生成dll
3.在使用时，将2中生成的dll先引用，再使用。
使用例子：
Imports Hardware
Public Class WebForm1
    Inherits System.Web.UI.Page
#Region " Web 窗体设计器生成的代码 "
    '该调用是 Web 窗体设计器所必需的。
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
    End Sub
    '注意: 以下占位符声明是 Web 窗体设计器所必需的。
    '不要删除或移动它。
    Private designerPlaceholderDeclaration As System.Object
    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: 此方法调用是 Web 窗体设计器所必需的
        '不要使用代码编辑器修改它。
        InitializeComponent()
    End Sub
#End Region
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim abc As New HardwareInfo
        Response.Write("cpu序列号：" & abc.GetCpuID())
        Response.Write("<br>网卡mac地址：" & abc.GetMacAddress())
        Response.Write("<br>硬盘信息：" & abc.GetHardDiskID())
        Response.Write("<br>机器名：" & abc.GetHostName())
        'Response.Write("<br>网卡mac地址：" & abc.GetType())
    End Sub
End Class



    *******************************************************************/

    #endregion





/// <summary>
/// 获取计算机信息类
/// </summary>
    public class HardwareInfo
        {
        #region 结构体定义
        public enum NCBCONST
        {
            NCBNAMSZ = 16,      /* absolute length of a net name         */
            MAX_LANA = 254,      /* lana's in range 0 to MAX_LANA inclusive   */
            NCBENUM = 0x37,      /* NCB ENUMERATE LANA NUMBERS            */
            NRC_GOODRET = 0x00,      /* good return                              */
            NCBRESET = 0x32,      /* NCB RESET                        */
            NCBASTAT = 0x33,      /* NCB ADAPTER STATUS                  */
            NUM_NAMEBUF = 30,      /* Number of NAME's BUFFER               */
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct ADAPTER_STATUS
        {
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
            public byte[] adapter_address;
            public byte rev_major;
            public byte reserved0;
            public byte adapter_type;
            public byte rev_minor;
            public ushort duration;
            public ushort frmr_recv;
            public ushort frmr_xmit;
            public ushort iframe_recv_err;
            public ushort xmit_aborts;
            public uint xmit_success;
            public uint recv_success;
            public ushort iframe_xmit_err;
            public ushort recv_buff_unavail;
            public ushort t1_timeouts;
            public ushort ti_timeouts;
            public uint reserved1;
            public ushort free_ncbs;
            public ushort max_cfg_ncbs;
            public ushort max_ncbs;
            public ushort xmit_buf_unavail;
            public ushort max_dgram_size;
            public ushort pending_sess;
            public ushort max_cfg_sess;
            public ushort max_sess;
            public ushort max_sess_pkt_size;
            public ushort name_count;
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct NAME_BUFFER
        {
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.NCBNAMSZ)]
            public byte[] name;
            public byte name_num;
            public byte name_flags;
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct NCB
        {
            public byte ncb_command;
            public byte ncb_retcode;
            public byte ncb_lsn;
            public byte ncb_num;
            public IntPtr ncb_buffer;
            public ushort ncb_length;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.NCBNAMSZ)]
            public byte[] ncb_callname;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.NCBNAMSZ)]
            public byte[] ncb_name;
            public byte ncb_rto;
            public byte ncb_sto;
            public IntPtr ncb_post;
            public byte ncb_lana_num;
            public byte ncb_cmd_cplt;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
            public byte[] ncb_reserve;
            public IntPtr ncb_event;
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct LANA_ENUM
        {
            public byte length;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.MAX_LANA)]
            public byte[] lana;
        }
        [StructLayout(LayoutKind.Auto)]
        public struct ASTAT
        {
            public ADAPTER_STATUS adapt;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.NUM_NAMEBUF)]
            public NAME_BUFFER[] NameBuff;
        }
        public class Win32API
        {
            [DllImport("NETAPI32.DLL")]
            public static extern char Netbios(ref NCB ncb);
        }


        #endregion

        /// <summary> 
        ///  获取计算机名称
        /// </summary> 
        /// <returns></returns> 
       public string GetComputerName()
        {
            try
            {
                return System.Environment.GetEnvironmentVariable("ComputerName");
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }
        }

        /// <summary>
        /// 取网路Dns机器名
        /// </summary>
        /// <returns></returns>
        public string GetHostName()
            {
                return System.Net.Dns.GetHostName();
            }
        /// <summary>
        ///   //取CPU编号
        /// </summary>
        /// <returns>CPU ID号</returns>
        public String GetCpuID()
            {
                try
                {
                    ManagementClass mc = new ManagementClass("Win32_Processor");
                    ManagementObjectCollection moc = mc.GetInstances();

                    String strCpuID = null;
                    foreach (ManagementObject mo in moc)
                    {
                        strCpuID = mo.Properties["ProcessorId"].Value.ToString();
                        break;
                    }
                    return strCpuID;
                }
                catch
                {
                    return "";
                }
            }//end method

        /// <summary>
        /// ///取第一块硬盘编号
        /// </summary>
        /// <returns>第一块硬盘编号</returns>
        public String GetFristHardDiskID()
            {
                try
                {
                    ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
                    String strHardDiskID = null;
                    foreach (ManagementObject mo in searcher.Get())
                    {
                        strHardDiskID = mo["SerialNumber"].ToString().Trim();
                        break;
                    }
                    return strHardDiskID;
                }
                catch
                {
                    return "";
                }
            }//end

        /// <summary>
        /// 去硬盘序列号单硬盘才行
        /// </summary>
        /// <returns></returns>
        public string GetDiskID()
        {
            try
            {
                //获取硬盘ID 
                String HDid = "";
                ManagementClass mc = new ManagementClass("Win32_DiskDrive");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    HDid = (string)mo.Properties["Model"].Value;
                }
                moc = null;
                mc = null;
                return HDid;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }

        }

        /// <summary> 
        /// 物理内存 
        /// </summary> 
        /// <returns></returns> 
       public string GetTotalPhysicalMemory()
        {
            try
            {

                string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {

                    st = mo["TotalPhysicalMemory"].ToString();

                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }
        }

        /// <summary> 
        /// PC 操作系统类型 
        /// </summary> 
        /// <returns></returns> 
      public  string GetSystemType()
        {
            try
            {
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {

                    st = mo["SystemType"].ToString();

                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }

        }

        /// <summary> 
        /// 操作系统的登录用户名 
        /// </summary> 
        /// <returns></returns> 
 
        public    string GetUserName()
        {
            try
            {
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {

                    st = mo["UserName"].ToString();

                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }

        }

      
       /// <summary>
       /// 获得单网卡ip地址包括虚拟ip
       /// </summary>
       /// <returns></returns>
        public  string GetIPAddress()
        {
            try
            {
                //获取IP地址 
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if ((bool)mo["IPEnabled"] == true)
                    {
                        //st=mo["IpAddress"].ToString(); 
                        System.Array ar;
                        ar = (System.Array)(mo.Properties["IpAddress"].Value);
                        st = ar.GetValue(0).ToString();
                        break;
                    }
                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }

        }
        /// <summary>
        /// 获得单网卡ip地址包括虚拟ip
        /// </summary>
        /// <returns></returns>
        public string GetLocalIp()
        {
            
            ///获取本地的IP地址
            string AddressIP = string.Empty;
            foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
               
                if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                {
                 
                       AddressIP = _IPAddress.ToString();
                }
            }
            return AddressIP;
        }

     /// <summary>
     /// 获得物理网卡IP地址列表 包括IPV4 和IPV6
     /// </summary>
     /// <returns>ip地址列表</returns>
        public List<string> GetPhysicMacAdressList()
        {
            List<string> ipAdresslist=new List<string>();
            ManagementClass mc_nac = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc_nac = mc_nac.GetInstances();
            foreach (ManagementObject mo in moc_nac)
            {
                string mServiceName = mo["ServiceName"] as string;
                //过滤非真实的网卡
                if (!(bool)mo["IPEnabled"])
                { continue; }
                if (mServiceName.ToLower().Contains("vmnetadapter")
                   || mServiceName.ToLower().Contains("ppoe")
                   || mServiceName.ToLower().Contains("bthpan")
                   || mServiceName.ToLower().Contains("tapvpn")
                    || mServiceName.ToLower().Contains("ndisip")
                     || mServiceName.ToLower().Contains("sinforvnic"))
                { continue; }


                bool mDHCPEnabled = (bool)mo["IPEnabled"];
                string mCaption = mo["Caption"] as string;
                string mMACAddress = mo["MACAddress"] as string;
                string[] mIPAddress = mo["IPAddress"] as string[];
                string[] mIPSubnet = mo["IPSubnet"] as string[];
                string[] mDefaultIPGateway = mo["DefaultIPGateway"] as string[];
                string[] mDNSServerSearchOrder = mo["DNSServerSearchOrder"] as string[];
                if (mIPAddress != null)
                {

                    foreach (string ip in mIPAddress)
                    {
                        if (ip != "0.0.0.0")
                        {
                             ipAdresslist.Add(ip);
                           
                        }
                    }
                }
                
                mo.Dispose();
            }
        return ipAdresslist;
        }

/// <summary>
 /// 获取网卡物理Mac地址
 /// </summary>
 /// <returns></returns>
  public string GetPhysicLocalMacAddr()
 {
         string madAddr = null;
        ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
        ManagementObjectCollection moc2 = mc.GetInstances();
         foreach (ManagementObject mo in moc2)
         {
                if (Convert.ToBoolean(mo["IPEnabled"]) == true)
                    {
                        madAddr = mo["MacAddress"].ToString();
                       madAddr = madAddr.Replace(':', '-');
                 }
                 mo.Dispose();
           }
         return madAddr;
    }


    }
}

